import Koa from 'koa';
const app: Koa = new Koa();

import Debug from 'debug';
const debug = Debug('http');

import views from 'koa-views';
import bodyParser from 'koa-bodyparser';
import cors from 'koa-cors'
import serve from 'koa-static';
import jwt from 'koa-jwt'
import index from './routes/index';
import users from './routes/users';
import list from './routes/list';

app.use(cors())

app.use(function (ctx, next) {
    return next().catch((err) => {
        if (401 == err.status) {
            ctx.status = 401;
            ctx.body = 'Protected resource, use Authorization header to get access\n';
        } else {
            throw err;
        }
    });
});
// 

// body parser
app.use(bodyParser({
    enableTypes: ['json', 'form', 'text']
}));

app.use(serve(__dirname + '/public'));
app.use(views(__dirname + '/views', {
    extension: 'pug'
}));

// logger
app.use(async (ctx: Koa.Context, next: Function) => {
    const start: number = Date.now();
    await next();
    const now: number = Date.now();
    const ms = now - start;
    debug(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes()).use(index.allowedMethods());
app.use(users.routes()).use(users.allowedMethods());
app.use(list.routes()).use(list.allowedMethods());
app.use(jwt({ secret: 'byp' }).unless({ path: [/^\/public/] }));

// error-handling
app.on('error', (err: Error, ctx: Koa.Context) => {
    console.error('server error', err, ctx)
});

export default app;
